package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    private IRegionService regionService;

    @RequestMapping("list")
    public String list(@ModelAttribute("qo") QueryObject qo, Model model, HttpSession session){
        return "/region/list";
    }

    @RequestMapping("getRegionByParentId")
    @ResponseBody
    public Object getRegionByParentId(Long parentId){
        List<Region> regions = regionService.getRegionByParentId(parentId);
        //为了treeview能识别返回数据,需要进行额外转换
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (Region region : regions){
            mapList.add(region.toMap());
        }
        return mapList;
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region){
        JSONResult result = new JSONResult();
        try {
            regionService.saveOrUpdate(region);
        }catch (Exception e){
            result.mark(e.getMessage());
        }
        return result;
    }
}
